package com.sdhs.paas.authclient.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.Recover;
import org.springframework.scheduling.annotation.Scheduled;

import com.sdhs.paas.authclient.config.ServiceAuthConfig;
import com.sdhs.paas.authclient.config.UserAuthConfig;
import com.sdhs.paas.authclient.service.ServiceAuthFeign;
import com.sdhs.paas.authshare.common.msg.ObjectRestResponse;

import dto.ClientDTO;

/**
 * 监听完成时触发
 *
 * @author ace
 * @create 2017/11/29.
 */
@Configuration
public class AuthClientRunner implements CommandLineRunner {
//	private static Logger log  = LoggerFactory.getLogger(AuthClientRunner.class); 
	
    @Autowired
    private ServiceAuthConfig serviceAuthConfig;
    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private ServiceAuthFeign serviceAuthFeign;

    @Override
    public void run(String... args) throws Exception {
    	System.out.println("初始化加载用户pubKey");
//        log.info("初始化加载用户pubKey");
        try {
            refreshUserPubKey();
        }catch(Exception e){
        	System.out.println("初始化加载用户pubKey失败,1分钟后自动重试!");
//            log.error("初始化加载用户pubKey失败,1分钟后自动重试!",e);
        }
//        log.info("初始化加载客户pubKey");
        try {
            refreshServicePubKey();
        }catch(Exception e){
        	System.out.println("初始化加载客户pubKey失败,1分钟后自动重试!");
//            log.error("初始化加载客户pubKey失败,1分钟后自动重试!",e);
        }
    }
    @Scheduled(cron = "0 0/10 * * * ?")
    public void refreshUserPubKey(){
    	ClientDTO clientDTO =new ClientDTO();
    	clientDTO.setClientId(serviceAuthConfig.getClientId());
    	clientDTO.setSecret(serviceAuthConfig.getClientSecret());
    	ObjectRestResponse<ClientDTO> userResponse = serviceAuthFeign.getUserPublicKey(clientDTO);
        this.userAuthConfig.setPubKeyByte(userResponse.getData().getKey());
    }
    @Scheduled(cron = "0 0/10 * * * ?")
    @Recover
    public void refreshServicePubKey(){
    	ClientDTO clientDTO =new ClientDTO();
    	clientDTO.setClientId(serviceAuthConfig.getClientId());
    	clientDTO.setSecret(serviceAuthConfig.getClientSecret());
    	ObjectRestResponse<ClientDTO> serviceResponse = serviceAuthFeign.getServicePublicKey(clientDTO);
        this.serviceAuthConfig.setPubKeyByte(serviceResponse.getData().getKey());
    }

}